package com.tyc.es.utills;

import com.alibaba.fastjson.JSONObject;
import com.tyc.es.model.ESIndex;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: tyc
 * @CreateDate: 2021/1/8 10:51
 */
@Component
public class ESUtill<T> {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    boolean indexIsExsit(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        return exists;
    }

     GetResponse getById(String id) throws IOException {
        GetRequest request = new GetRequest(ESIndex.TB.getValue(), id);
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if(exists){
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            return response;
        }else {
            return null;
        }
    }

    boolean addOne(T t,String id) throws IOException {
        IndexRequest indexRequest = new IndexRequest("ESIndex.TB.getValue()");
        indexRequest.source(JSONObject.toJSONString(t),XContentType.JSON);
        indexRequest.id(id);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        RestStatus status = response.status();
        return status == RestStatus.OK?true:false;
    }

    boolean addAll(List<T> list) throws IOException {
        BulkRequest bulkRequest = new BulkRequest(ESIndex.TB.getValue());
        for (int i = 0; i < list.size(); i++) {
            String id = String.valueOf(i+1);
            bulkRequest.add(
                    new IndexRequest(ESIndex.TB.getValue()).id(id).source(JSONObject.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }



}
